#region  == Copyright == 
// =====================================================================
//  Microsoft Consulting Services France - Aymeric Mouillé - 2013
//  Projet     : CRM Solution Management Tool
//  Fichier    : SolutionImport.cs (30/04/2013 20:34)
//  
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// =====================================================================
#endregion

namespace CRM.Solution.Management.Tool
{
    #region  == Using == 
    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Threading;
    using System.Windows.Forms;

    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;

    #endregion

    public partial class SolutionImport : Form
    {
        private MainForm MainForm;

        private readonly BackgroundWorker bgSolutionImport;

        #region = Constructor =
        /// <summary>
        /// Initializes a new instance of the <see cref="SolutionImport" /> class.
        /// </summary>
        public SolutionImport(MainForm mainForm)
        {
            InitializeComponent();
            bgSolutionImport = new BackgroundWorker();
            bgSolutionImport.DoWork += bgSolutionImport_DoWork;
            MainForm = mainForm;
        }
        #endregion

        #region Btn Browse Click
        /// <summary>
        /// Handles the Click event of the btnBrowse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="EventArgs" /> instance containing the event data.
        /// </param>
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtSolutionFilePath.Text = openFileDialog.FileName;
            }
        }
        #endregion

        #region Btn Cancel Click
        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="EventArgs" /> instance containing the event data.
        /// </param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion

        #region Btn Import Click
        /// <summary>
        /// Handles the Click event of the btnImport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="EventArgs" /> instance containing the event data.
        /// </param>
        private void btnImport_Click(object sender, EventArgs e)
        {
            MainForm.CurrentSolutionImportJobId = Guid.Empty;

            // ReAssign WorkFlow to current CRM user
            if (chkReassignWorkflows.Checked)
            {
                var whoAmIRequest = new WhoAmIRequest();
                var whoAmIResponse = (WhoAmIResponse)MainForm.OrganizationService.Execute(whoAmIRequest);
                var currentUserReference = new EntityReference("systemuser", whoAmIResponse.UserId);
                var qe = new QueryExpression("workflow") { ColumnSet = new ColumnSet(new[] { "name" }) };
                qe.Criteria.AddCondition("ownerid", ConditionOperator.NotEqualUserId);

                var workflows = MainForm.OrganizationService.RetrieveMultiple(qe).Entities;
                foreach (var workflow in workflows)
                {
                    var request = new AssignRequest { Assignee = currentUserReference, Target = workflow.ToEntityReference() };
                    MainForm.OrganizationService.Execute(request);
                }
            }
            bgSolutionImport.RunWorkerAsync(txtSolutionFilePath.Text);
            Thread.Sleep(1000);
            MainForm.SwitchToSolutionImportProgress();
            Close();
        }
        #endregion

        #region Bg Solution Import Do Work
        /// <summary>
        /// Handles the DoWork event of the bgSolutionImport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="DoWorkEventArgs" /> instance containing the event data.
        /// </param>
        private void bgSolutionImport_DoWork(object sender, DoWorkEventArgs e)
        {
            MainForm.CurrentSolutionImportJobId = Guid.NewGuid();
            var solutionFileBytes = File.ReadAllBytes(e.Argument.ToString());
            var importSolutionRequest = new ImportSolutionRequest { CustomizationFile = solutionFileBytes, PublishWorkflows = chkPublishWorkflows.Checked, ImportJobId = MainForm.CurrentSolutionImportJobId, OverwriteUnmanagedCustomizations = chkOverwriteUnmanagedCustomizations.Checked };

            MainForm.OrganizationService.Execute(importSolutionRequest);
        }
        #endregion
    }
}
